﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;

namespace TfsExtensions.Build.Activities
{
    public sealed class InvokeXslTranformForReflectionXml : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> ReflectionOrgFilename { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleTransformsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleProductionToolsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolderName { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleFormatXsl { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleFileNameXsl { get; set; }

        [RequiredArgument]
        public InArgument<string> ReflectionXMLFilename { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // this activity runs following command.
            //<Exec Command="&quot;$(TransformEXE)&quot; /xsl:&quot;$(SandcastleTransformsFolder)\$(SandcastleFormatXsl)&quot; /xsl:&quot;$(SandcastleTransformsFolder)\$(SandcastleFileNameXsl)&quot; $(WorkingFolderName)\$(ReflectionOrgFilename) /out:$(WorkingFolderName)\$(ReflectionXMLFilename) $(SandcastleArguments)" />

            var exeFileName = string.Format(@"{0}\XslTransform.exe", this.SandcastleProductionToolsFolder.Get(context));

            var transformsFolder = "/xsl:\"" + string.Format(@"{0}\{1}", this.SandcastleTransformsFolder.Get(context), this.SandcastleFormatXsl.Get(context)) + "\"";
            var transformsFileName = "/xsl:\"" + string.Format(@"{0}\{1}", this.SandcastleTransformsFolder.Get(context), this.SandcastleFileNameXsl.Get(context)) + "\"";


            var workingFolder = "\"" + string.Format(@"{0}\{1}", this.WorkingFolderName.Get(context), this.ReflectionOrgFilename.Get(context)) + "\"";

            var path = "\"" + string.Format("{0}\\{1}", this.WorkingFolderName.Get(context), this.ReflectionXMLFilename.Get(context)) + "\"";

            var arguments = string.Format("{0} {1} {2} /out:{3} /arg:IncludeAllMembersTopic=true /arg:IncludeInheritedOverloadTopics=true", transformsFolder, transformsFileName, workingFolder, path);
            
            try
            {
                InvokeCommand.ExecuteCommand(context, exeFileName, arguments);
            }
            catch(Exception ex)
            {
                LogHelper.LogError(context, ex.Message);
                throw;
            }
        }
    }
}
